package com.libinshen.wxpay.common.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.libinshen.wxpay.common.constant.Constants;
import com.libinshen.wxpay.videoAliBaBa.entity.easyExcel.TeacherEasyExcel;
import com.libinshen.wxpay.videoAliBaBa.mapper.TeacherMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lbs
 */
@Slf4j
public class ExcelListener implements ReadListener<TeacherEasyExcel> {

    private TeacherMapper teacherMapper;

    //针对大批量数据，创建分批次list
    List<TeacherEasyExcel> list = new ArrayList<>();

    public ExcelListener() {
    }

    public ExcelListener(TeacherMapper teacherMapper) {
        this.teacherMapper = teacherMapper;
    }

    /**
     * 遍历每一行的记录
     *
     * @param teacherEasyExcel
     * @param analysisContext
     */
    @Override
    public void invoke(TeacherEasyExcel teacherEasyExcel, AnalysisContext analysisContext) {
        log.info("解析到一条记录：{}：", teacherEasyExcel);
        //处理读取出来的数据

        list.add(teacherEasyExcel);
        log.info("list中的数据：", list);
        if (list.size() > Constants.BATCH_COUNT) {
            //批量将数据insert进去数据库
            teacherMapper.batchInsert(list);
            log.info("数据批量插入成功");
            list.clear();
        }
    }

    /**
     * 所有数据读取之后的收尾工作
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("全部数据解析完成");
        log.info("list", list);
        teacherMapper.batchInsert(list);
    }
}
